package com.lh.project.interceptor;

import cn.hutool.jwt.JWTUtil;
import com.lh.project.common.ErrorCode;
import com.lh.project.common.JwtUtil;
import com.lh.project.common.UserHolder;
import com.lh.project.exception.JWTException;
import com.lh.project.model.vo.UserVO;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.jar.JarException;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //获取token
//        String token = request.getHeader("token");
//        if(token==null||token.length()==0){
//            throw  new JWTException(ErrorCode.TOKEN_ERROR);
//        }
//        boolean verify = JwtUtil.verify(token);
//        if(!verify){
//            throw new JWTException(ErrorCode.TOKEN_ERROR);
//        }else{
//            //将用户封装到UserHolder中
//            UserVO user = JwtUtil.getUser(token);
//            UserHolder.saveUserVO(user);
//            System.out.println("只在登录的用户是："+user);
//            return true;
//        }
        if(UserHolder.getUser()==null){
            //说明用户没有携带token，还敢请求被拦截的路径，杀
            throw new JWTException(ErrorCode.TOKEN_ERROR);
        }
        //有UserHolder.getUser()的话，放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户，避免内存泄露
        UserHolder.removeUser();
    }
}
